<template>
  <div class="order-push">
    <el-card class="box-card" shadow="never">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="订单编号">
            <el-input v-model="searchForm.order_no" placeholder="请输入订单编号"></el-input>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="searchForm.status" placeholder="请选择订单状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="待付款" value="10"></el-option>
              <el-option label="待发货" value="20"></el-option>
              <el-option label="已发货" value="30"></el-option>
              <el-option label="已完成" value="40"></el-option>
              <el-option label="已取消" value="50"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下单时间">
            <el-date-picker
              v-model="searchForm.date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handlePush" :loading="pushLoading">推送订单</el-button>
        <el-button type="success" @click="handleExport">导出订单</el-button>
        <el-button
          type="primary"
          :disabled="selectedOrders.length === 0"
          @click="handlePushSingle"
        >
          推送ERP
        </el-button>
      </div>

      <!-- 订单列表 -->
      <el-table
        v-loading="loading"
        :data="orderList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="order_id" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="trade_no" label="交易编号" width="200"></el-table-column>
        <el-table-column prop="total_price" label="订单总额" width="120">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.total_price?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods_total" label="商品总额" width="120">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.goods_total?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="delivery_fee" label="运费" width="100">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.delivery_fee?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="payment_method" label="支付方式" width="120"></el-table-column>
        <el-table-column prop="order_status" label="订单状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getOrderStatusType(scope.row.order_status)">
              {{ getOrderStatusText(scope.row.order_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payment_status" label="支付状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.payment_status === '1' ? 'success' : 'warning'">
              {{ scope.row.payment_status === '1' ? '已支付' : '未支付' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="160"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleViewOrder(scope.row)">查看</el-button>
            <el-button 
              size="mini" 
              type="success" 
              @click="handlePushSingle(scope.row)"
              :disabled="scope.row.push_status === 1"
            >推送</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisible"
      width="70%"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentOrder.order_id }}</el-descriptions-item>
          <el-descriptions-item label="交易编号">{{ currentOrder.trade_no }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(currentOrder.order_status)">
              {{ getOrderStatusText(currentOrder.order_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="currentOrder.payment_status === '1' ? 'success' : 'warning'">
              {{ currentOrder.payment_status === '1' ? '已支付' : '未支付' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单总额">¥{{ currentOrder.total_price?.toFixed(2) || '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="商品总额">¥{{ currentOrder.goods_total?.toFixed(2) || '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="运费">¥{{ currentOrder.delivery_fee?.toFixed(2) || '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ currentOrder.payment_method }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.create_time }}</el-descriptions-item>
        </el-descriptions>

        <div class="order-goods" style="margin-top: 20px;">
          <h3>商品信息</h3>
          <el-table :data="currentOrder.goods" border style="width: 100%">
            <el-table-column prop="goods_name" label="商品名称"></el-table-column>
            <el-table-column prop="spec_name" label="规格" width="150"></el-table-column>
            <el-table-column prop="price" label="单价" width="120">
              <template slot-scope="scope">
                <span class="price">¥{{ scope.row.price?.toFixed(2) || '0.00' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="num" label="数量" width="100"></el-table-column>
            <el-table-column prop="total" label="小计" width="120">
              <template slot-scope="scope">
                <span class="price">¥{{ (scope.row.price * scope.row.num)?.toFixed(2) || '0.00' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, pushOrder, getOrderDetail, exportOrders } from '@/api/order'

export default {
  name: 'OrderPush',
  data() {
    return {
      // 搜索表单
      searchForm: {
        order_no: '',
        status: '',
        date_range: []
      },
      // 分页信息
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 订单列表
      orderList: [],
      // 加载状态
      loading: false,
      pushLoading: false,
      // 选中的订单
      selectedOrders: [],
      // 对话框
      dialogVisible: false,
      currentOrder: null
    }
  },
  created() {
    this.fetchOrders()
  },
  methods: {
    // 获取订单列表
    async fetchOrders() {
      try {
        this.loading = true
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          ...this.searchForm
        }
        const res = await getOrderList(params)
        this.orderList = res.data.data.orders
        this.total = res.data.data.total
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.$message.error('获取订单列表失败')
      } finally {
        this.loading = false
      }
    },
    // 处理搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchOrders()
    },
    // 重置搜索
    handleReset() {
      this.searchForm = {
        order_no: '',
        status: '',
        date_range: []
      }
      this.handleSearch()
    },
    // 处理分页变化
    handlePageChange(page) {
      this.currentPage = page
      this.fetchOrders()
    },
    // 处理每页条数变化
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.fetchOrders()
    },
    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedOrders = selection
    },
    // 处理推送
    async handlePush() {
      if (this.selectedOrders.length === 0) {
        this.$message.warning('请选择要推送的订单')
        return
      }

      try {
        this.pushLoading = true
        const orderIds = this.selectedOrders.map(order => order.order_id)
        await pushOrder({ order_ids: orderIds })
        this.$message.success('推送成功')
        this.fetchOrders()
      } catch (error) {
        console.error('推送订单失败:', error)
        this.$message.error('推送订单失败')
      } finally {
        this.pushLoading = false
      }
    },
    // 处理导出
    async handleExport() {
      try {
        const params = {
          ...this.searchForm
        }
        await exportOrders(params)
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出订单失败:', error)
        this.$message.error('导出订单失败')
      }
    },
    // 处理查看订单
    async handleViewOrder(row) {
      try {
        const res = await getOrderDetail(row.order_id)
        this.currentOrder = res.data
        this.dialogVisible = true
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败')
      }
    },
    // 处理单个推送
    async handlePushSingle(row) {
      try {
        await pushOrder({ order_ids: [row.order_id] })
        this.$message.success('推送成功')
        this.fetchOrders()
      } catch (error) {
        console.error('推送订单失败:', error)
        this.$message.error('推送订单失败')
      }
    },
    // 获取订单状态类型
    getOrderStatusType(status) {
      const statusMap = {
        '1': 'warning',
        '2': 'primary',
        '3': 'success',
        '4': 'success',
        '5': 'info'
      }
      return statusMap[status] || 'info'
    },
    // 获取订单状态文本
    getOrderStatusText(status) {
      const statusMap = {
        '1': '待付款',
        '2': '待发货',
        '3': '已发货',
        '4': '已完成',
        '5': '已取消'
      }
      return statusMap[status] || '未知状态'
    }
  }
}
</script>

<style lang="scss" scoped>
.order-push {
  .search-bar {
    margin-bottom: 20px;
  }

  .toolbar {
    margin-bottom: 20px;
  }

  .price {
    color: #F56C6C;
    font-weight: 500;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .order-goods {
    h3 {
      margin: 0 0 15px;
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }
}
</style> 